package com.sskj.market.ui.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Color;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.sskj.common.base.App;
import com.sskj.common.rxbus2.RxBus;
import com.sskj.common.util.CheckUtil;
import com.sskj.common.util.ClickUtil;
import com.sskj.common.util.ToastUtil;
import com.sskj.lib.RConfig;
import com.sskj.lib.base.BaseActivity;
import com.sskj.market.R;
import com.sskj.market.R2;
import com.sskj.market.bean.AreaBean;
import com.sskj.market.bean.MyAddressBean;
import com.sskj.market.presenter.AddAddressPresenter;
import com.sskj.market.util.GetJsonDataUtil;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;

/**
 * @author Hey
 * Create at  2019/07/26
 */
@Route(path = RConfig.MARKET_ADD_ADDRESS)
public class AddAddressActivity extends BaseActivity<AddAddressPresenter> {

    @BindView(R2.id.tvTitle)
    TextView tvTitle;
    @BindView(R2.id.tvReturn)
    TextView tvReturn;
    @BindView(R2.id.etAddressName)
    EditText etAddressName;
    @BindView(R2.id.etAddressNumber)
    EditText etAddressNumber;
    @BindView(R2.id.rlAddressAddress)
    RelativeLayout rlAddressAddress;
    @BindView(R2.id.etDetailAddress)
    EditText etDetailAddress;
    @BindView(R2.id.cbAddress)
    CheckBox cbAddress;
    @BindView(R2.id.btAddress)
    Button btAddress;
    @BindView(R2.id.tvShOuHuoDiZhi)
    TextView tvShOuHuoDiZhi;
    @BindView(R2.id.etAddress)
    TextView etAddress;
    private List<AreaBean> options1Items = new ArrayList<>();
    private ArrayList<ArrayList<String>> options2Items = new ArrayList<>();
    private ArrayList<ArrayList<ArrayList<String>>> options3Items = new ArrayList<>();

    private String city;
    private String provinces;
    private String country;

    @Override
    public int getLayoutId() {
        return R.layout.market_activity_add_address;
    }

    @Override
    public AddAddressPresenter getPresenter() {
        return new AddAddressPresenter();
    }

    @Override
    public void initView() {
        tvTitle.setText(App.INSTANCE.getString(R.string.market_addAddressActivity1));
        tvReturn.setVisibility(View.VISIBLE);
        initJsonData();
        ClickUtil.click(300, etAddress, () -> {

            //隐藏软键盘
            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            if (imm != null) {
                imm.hideSoftInputFromWindow(getWindow().getDecorView().getWindowToken(), 0);
            }
            showPickerView();
        });

        ClickUtil.click(300, btAddress, () -> {
            if (!CheckUtil.isMobile(etAddressNumber.getText().toString())){
                ToastUtil.showShort(App.INSTANCE.getString(R.string.market_addAddressActivity2));
                return;
            }
            mPresenter.addAddress(etAddressName.getText().toString()
                    , etAddressNumber.getText().toString()
                    , provinces
                    , city
                    , country
                    , etDetailAddress.getText().toString()
                    , cbAddress.isChecked() ? "1" : "0",true);
        });
    }


    // 弹出选择器
    private void showPickerView() {
        @SuppressLint("SetTextI18n") OptionsPickerView pvOptions = new OptionsPickerBuilder(this, (options1, options2, options3, v) -> {

            //返回的分别是三个级别的选中位置
            provinces = options1Items.size() > 0 ?
                    options1Items.get(options1).getPickerViewText() : "";

            city = options2Items.size() > 0
                    && options2Items.get(options1).size() > 0 ?
                    options2Items.get(options1).get(options2) : "";

            country = options2Items.size() > 0
                    && options3Items.get(options1).size() > 0
                    && options3Items.get(options1).get(options2).size() > 0 ?
                    options3Items.get(options1).get(options2).get(options3) : "";


            etAddress.setText(provinces + "  " + city + "  " + country);
            etAddress.setTextColor(getResources().getColor(R.color.white));
//
        })

                .setTitleText(App.INSTANCE.getString(R.string.market_addAddressActivity3))
                .setDividerColor(Color.GRAY)
                //设置选中项文字颜色
                .setTextColorCenter(Color.BLACK)
                //确定和取消文字大小
                .setSubCalSize(18)
                //标题文字大小
                .setTitleSize(20)
                //标题文字颜色
                .setTitleColor(Color.BLACK)
                //滚轮文字大小
                .setContentTextSize(22)
                //循环与否
                .setCyclic(false, false, false)
                //点击外部dismiss default true
                .setOutSideCancelable(false)
                //是否显示为对话框样式
                .isDialog(false)
                //切换时是否还原，设置默认选中第一项。
                .isRestoreItem(true)
                .build();

        //三级选择器
        //noinspection unchecked
        pvOptions.setPicker(options1Items, options2Items, options3Items);
        pvOptions.show();
    }

    private void initJsonData() {//解析数据

        //获取assets目录下的json文件数据
        String json = GetJsonDataUtil.getJson(this, "province.json");
        //用Gson 转成实体
        ArrayList<AreaBean> jsonBean = parseData(json);

        options1Items = jsonBean;

        //遍历省份
        for (int i = 0; i < jsonBean.size(); i++) {
            //该省的城市列表（第二级）
            ArrayList<String> cityList = new ArrayList<>();
            //该省的所有地区列表（第三级）
            ArrayList<ArrayList<String>> provinceAreaList = new ArrayList<>();

            //遍历该省份的所有城市
            for (int c = 0; c < jsonBean.get(i).getCity().size(); c++) {
                String cityName = jsonBean.get(i).getCity().get(c).getName();
                //添加城市
                cityList.add(cityName);
                //该城市的所有地区列表
                ArrayList<String> cityAreaList = new ArrayList<>();
                if (jsonBean.get(i).getCity().get(c).getArea() == null
                        || jsonBean.get(i).getCity().get(c).getArea().size() == 0) {
                    cityAreaList.add("");
                } else {
                    cityAreaList.addAll(jsonBean.get(i).getCity().get(c).getArea());
                }
                //添加该省所有地区数据
                provinceAreaList.add(cityAreaList);
            }

            /*
             * 添加城市数据
             */
            options2Items.add(cityList);

            /*
             * 添加地区数据
             */
            options3Items.add(provinceAreaList);
        }

    }


    public ArrayList<AreaBean> parseData(String result) {
        //Gson 解析
        return new Gson().fromJson(result, new TypeToken<ArrayList<AreaBean>>() {
        }.getType());
    }

    /**
     * 添加地址成功回调刷新数据
     * <p>
     * {@link  com.sskj.market.ui.activity.MyAddressActivity#refreshList(MyAddressBean)}
     */
    public void addAddressSuccess() {
        MyAddressBean bean = new MyAddressBean();
        RxBus.getDefault().post(bean);
        finish();
    }


}
